
import json
from util import logger
from datetime import datetime
import requests
from ns import Ns
from setting import NS_HOST
from util import parse_ascII_to_command, send_message_by_websocket

NS_HOST = "192.168.31.101:8080"

class BleFunction:

    def __init__(self, master_host, base_station_mac) -> None:
        
        self.master_host = master_host

        self.base_station_mac = base_station_mac

        self.ns = Ns(NS_HOST)

    
    def get_node_tree(self):
        '''获取nodetree'''

        url = f"http://{self.master_host}:8080/get_node_tree"

        try:

            r= requests.get(url, params={"base_station_mac": self.base_station_mac})

        
        except Exception as e:

            logger.error(f"get_node_tree: {str(e)}")

            with open("node_tree.txt") as f:

                result = f.read()

        else:

            with open("node_tree.txt", "w") as f:

                f.write(r.text)

            result = r.json()

        return result
    
    def get_sensor_last_data(self, sensor_mac):
        '''获取最新sensor最新数据'''

        data = self.ns.get_rxframes_list_by_devaddr(sensor_mac)[0]

        data  = data.get("data")

        return parse_ascII_to_command(data).decode("utf-8")
    
    def get_sensor_last_data_(self, sensor_mac):
        '''获取最新sensor最新数据'''

        data = self.ns.get_rxframes_list_by_devaddr(sensor_mac)[0]


        return data

    def get_sensor_info(self):
        '''获取蓝牙所需要的传感器信息'''

        node_tree = self.get_node_tree()

        for node in node_tree["resultBody"]["sensors_info"]:

            try:

                info_data = self.get_sensor_last_data_(node["mac"])

                node["value"] = info_data["data"]
                datetime_obj = datetime.strptime(info_data["datetime"], '%Y-%m-%dT%H:%M:%S.%fZ')
                node["value_last_time"] = int(datetime.timestamp(datetime_obj))

            except Exception as e:

                logger.error(f"get_sensor_value_error: {str(e)}")

                node["value"] = None
                node["value_last_time"] = None

        return node_tree
    
    def get_sensor_last_data_continuous(self, command, sensor_mac):
        ''''''




if __name__ == "__main__":

    from setting import MQTT_LOCAL_HOST, get_mac_address

    # base_station_mac = get_mac_address()

    # bf = BleFunction(MQTT_LOCAL_HOST, base_station_mac)

    # base_station_mac = "1671CFFFFE8E831B"

    bf = BleFunction("192.168.31.120", "1671CFFFFE8E831B")

    i = bf.get_sensor_info()

    print(i)

    # def set_host(self, order_dict):
    #     '''order_dict:
    #     {
    #         "task_type": "set_host",
    #         "task_id": "2",	# 任务ID号
    #         "data": {
    #             "host": "192.168.33.33",
    #             "netmask": "255.255.255.0"
    #         }
    #     }
    #     '''

    #     if not order_dict["task_type"] == "set_host":

    #         return {
    #             "type": "callback", 
    #             "data": {
    #                 "task_type": "set_host", 
    #                 "task_id": order_dict["task_id"], 
    #                 "result": "命令格式错误"
                
    #             }
    #         }
        
    #     with open("ble_set_host.conf", 'w') as f:

    #         f.write(json.dumps(order_dict))

    #     return {
    #         "type": "callback", 
    #         "data": {
    #             "task_type": "set_host", 
    #             "task_id": order_dict["task_id"], 
    #             "result": "success"
            
    #         }
    #     }

    # def get_base_info_(self):
    #     '''order_dict:
    #     {
    #         "task_type": "get_base_info",
    #         "task_id": "2",	# 任务ID号
    #         "data": ""
    #     }'''

    #     with DataBaseFunction() as df:

    #         base_staion_info = df.get_base_staion_info()

    #         brackets_info = df.get_brackets_info()

    #         sensors_info = df.get_sensors_info() # TODO 对应的最后一次要解析出来

    #     return {
    #         "type": "callback", 
    #         "data": {
    #             "task_type": "get_sensor_info", 
    #             "task_id": "2", 
    #             "result":{
    #                 "base_staion_info": base_staion_info,
    #                 "brackets_info": brackets_info,
    #                 "sensors_info": sensors_info

    #             }
    #         }

    #     }
    
    # def get_base_info(self, order_dict):
    #     '''order_dict:
    #     {
    #         "task_type": "get_base_info",
    #         "task_id": "2",	# 任务ID号
    #         "data": ""
    #     }'''

    #     with DataBaseFunction() as df:

    #         base_staion_info = df.get_base_staion_info()

    #     return {
    #         "type": "callback", 
    #         "data": {
    #             "task_type": "get_base_info", 
    #             "task_id": order_dict["task_id"], 
    #             "result":{
    #                 "base_staion_info": base_staion_info,
    #             }
    #         }

    #     }
    
    # def get_sensor_info(self, order_dict):

    #     '''{
    #         "task_type": "get_sensor_info",
    #         "task_id": "2",	# 任务ID号
    #         "data": {"base_station_id": 1}
    #     }'''

    #     base_station_id = order_dict["data"]["base_station_id"]

    #     with DataBaseFunction() as df:

    #         base_station_info = df.get_base_station_info_by_id(base_station_id)

    #         brackets_info = df.get_brackets_info_by_base_station_id(base_station_id)

    #         sensors_info = []

    #         for brackets in brackets_info:

    #             info = df.get_sensors_info_by_brackets_id(brackets["id"])

    #             sensors_info.extend(info)

    #     result =  {
    #         "base_staion_info": base_station_info,
    #         "brackets_info": brackets_info,
    #         "sensors_info": sensors_info
    #     }

    #     return {
    #             "type": "callback", 
    #             "data": {
    #                 "task_type": "get_sensor_info", 
    #                 "task_id": order_dict["task_id"], 
    #                 "result": result
    #             }
    #     }
    
    # def set_acquisition_cycle(self, order_dict):
    #     '''
    #     {
    #         "task_type": "set_acquisition_cycle",													
    #         "task_id": "183",																		# 任务ID号
    #         "data": {
    #             "devaddr_list": ["943EBDE7", "92B18DD5"],
    #             "value": "00"  # 00:不采集; 01:连续采集; 02:1秒一次; 03:5秒一次; 04:10秒一次； 05：30秒一次； 
    #         }
    #     }
    #     '''

    #     with DataBaseFunction() as df:

    #         df.insert_task(task_info=order_dict)


    #     return {
    #             "type": "callback", 
    #             "data": {
    #                 "task_type": "set_acquisition_cycle", 
    #                 "task_id": order_dict["task_id"], 
    #                 "task_status": "receive", 
    #                 "notes": None, 
    #                 "result": None
    #             }
    #     }
    
    # def get_task_status(self, order_dict):
         
    #     '''{
    #             "task_type": "get_task_status",
    #             "task_id": "2",	# 任务ID号
    #         }
    #     '''

    #     with DataBaseFunction() as df:

    #         info = df.selete_tasks_by_id(order_dict["task_id"])

    #     return {
    #         "type": "callback",

    #         "data":{
    #             "task_type": info["task_type"],
    #             "task_id": info["task_id"], 
    #             "task_status": info["status"], 
    #             "notes": None, 
    #             "result": info["return_data"], 
    #         }
    #     }
         




